<template>
  <BaseMainSlot>
    <template v-slot:zhactbar>
      <div class="page-top__wrapper">
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
          <CommonBtn :disabled="!addActive" @click="add">添加</CommonBtn>
          <CommonBtn :disabled="!delActive" @click="del">删除</CommonBtn>
        </div>
      </div>
    </template>
    <template v-slot:boxleft>
      <div class="zhtabletitle">已有摄像头</div>
      <el-table v-loading="loading" highlight-current-row :data="tableData" stripe border height="85%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="cameraName" label="摄像头名称" />
        <el-table-column prop="deviceSerial" label="序列号" />
        <el-table-column prop="solarEnergyCamera" label="开机预热">
          <template v-if="scope.row.cameraNo" slot-scope="scope">{{ scope.row.solarEnergyCamera === 'true' ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.cameraNo" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)"> <i class="el-icon-edit-outline"></i> 修 改 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:boxright>
      <div class="zhtabletitle">
        所有物联摄像头
        <el-cascader :options="options" :props="{ expandTrigger: 'hover', value: 'companyMark', children: 'child', label: 'ownershipName', checkStrictly: true }" clearable @change="ownership" />
      </div>
      <el-table ref="tableDatatwo" v-loading="loadingtwo" highlight-current-row :data="tableDatatwo" stripe border height="85%" @selection-change="handleSelectionChangetwo">
        <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="cameraName" label="摄像头名称" />
        <el-table-column prop="deviceSerial" label="序列号" />
        <el-table-column prop="solarEnergyCamera" label="开机预热">
          <template v-if="scope.row.cameraId" slot-scope="scope">{{ scope.row.solarEnergyCamera ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="verificationCode" label="验证码" />
      </el-table>
    </template>
    <template v-slot:dig>
      <el-dialog title="修改摄像头信息" :visible.sync="dialogFormVisible" width="400px">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="摄像头名称:" prop="cameraName" class="w100p">
            <el-input v-model="formData.cameraName" clearable />
          </el-form-item>
          <el-form-item label="是否开机预热:" prop="solarEnergyCamera" class="w100p">
            <el-select v-model="formData.solarEnergyCamera" disabled clearable>
              <el-option :value="'true'" label="是" />
              <el-option :value="'false'" label="否" />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogFormVisible = false">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="editmet">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import Pagination from '@/components/Pagination';
import nowpagereq from '@/api/processing-management/basic-info-manage/camera-basic-information';
import BaseMainSlot from '@/components/BaseMainSlot/basezuoyou.vue';
import { mymixin } from '@/utils/mixins';
import Axios from 'axios';
// import { getToken } from '@/utils/auth';
import * as utils from '@/utils/index';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'cameraBasicInformation',
  components: { Pagination, BaseMainSlot },
  mixins: [mymixin],
  inject: ['reload'],
  data() {
    return {
      // ----表格二号----
      loadingtwo: true,
      // 当前页
      currentPagetwo: 1,
      // 每页的数据条数
      pageSizetwo: 10,
      // 总条数
      totalSizetwo: 0,
      // 表格二号数据
      tableDatatwo: [],
      // 是否能输入
      // -------
      canInput: false,
      rules: {
        cameraName: [{ required: true, message: '摄像头名称不能为空', trigger: 'blur' }],
        solarEnergyCamera: [{ required: true, message: '请选择是否开机预热', trigger: 'change' }]
      },
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      dataTreeItemList: [],
      options: [],
      nowselectedListtwo: []
    };
  },
  watch: {},
  created() {
    this.getTableDataListone();
    this.getTableDataListtwo();
    this.getSelectlist();
  },
  mounted() {},
  methods: {
    // 获取当前拥有类型表格
    getTableDataListone() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          organizationNo: sessionStorage.organizationNo
        }
      };
      nowpagereq.ownFarmingTypelist(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error('当前摄像头表格获取失败');
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // // 赋值数组
        this.tableData = utils.addblankmet(data.content, this.pageSize);
        // this.addblankmet();
        this.resetActionBar();
        this.addActive = false;
      });
    },
    // 获取所有农业类型表格
    getTableDataListtwo(e) {
      this.loadingtwo = true;
      nowpagereq.getbaseFarmingTypeList(e || sessionStorage.organizationNo).then(res => {
        this.loadingtwo = false;
        if (res.code === 0) {
          this.$message.error('所有摄像头表格获取失败');
        }
        let data = res.data;
        // 赋值总条数
        // console.log(data)
        this.totalSizetwo = data.cameraList.length;
        // 赋值数组
        this.tableDatatwo = data.cameraList;
        // let cameraList = []
        data.cameraList.forEach(item => {
          if (data.cameraList.length % this.pageSizetwo) {
            // console.log(data.cameraList.length % this.pageSizetwo === 0, data.cameraList.length, this.pageSizetwo)
          }
        });
        if (this.tableDatatwo.length < this.pageSizetwo) {
          let havline = this.tableDatatwo.length % this.pageSizetwo;
          if (havline < this.pageSizetwo) {
            const remain = this.pageSizetwo - havline;
            for (var i = 0; i < remain; i++) {
              this.tableDatatwo.push({
                index: i + this.tableDatatwo.length - 1
              });
            }
          }
        }
        this.resetActionBar();
        this.addActive = false;
      });
    },
    async getSelectlist() {
      Axios({
        url: this.$cloudBaseurl + `ownership/queryTreeByCompanyMark?companyMark=${sessionStorage.organizationNo}`,
        method: 'get'
      }).then(res => {
        if (res.data.code === 1) {
          // this.getTableDataList();
          this.dataTreeItemList = [res.data.data];
          // console.log(res.data)
          this.options = this.filterArrForKey([res.data.data]);
          this.dialogFormVisible = false;
          // this.$message.success("查询成功！");
        } else {
          this.$message.warning('查询失败！');
        }
      });
    },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      if (arr === []) {
        return;
      }
      newArr = arr.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter(item => item != null);
      return newArr;
    },
    ownership(e) {
      // console.log(e)
      if (e) {
        let text = e.slice(-1);
        // console.log(text[0])
        this.getTableDataListtwo(text[0]);
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataListone();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataListone();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataListone();
    },
    changePageSizetwo(pageSize) {
      this.pageSizetwo = pageSize;
      this.getTableDataListtwo();
    },
    changeCurrentPagetwo(currentPage) {
      this.currentPagetwo = currentPage;
      // console.log(currentPage)
      // this.getTableDataListtwo();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.cameraNo;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSelectionChangetwo(list) {
      let nowselectedList = [];
      // let id = getToken('companyId')
      // organizationNo
      this.formData = {};
      nowselectedList = list.map(item => {
        return {
          ...item,
          solarEnergyCamera: item.solarEnergyCamera,
          verificationNo: item.verificationCode,
          organizationNo: sessionStorage.getItem('organizationNo')
        };
      });
      if (nowselectedList[0] !== undefined) {
        // this.formData = nowselectedList[0];
        // this.$set(this.formData, 'solarEnergyCamera', nowselectedList[0].solarEnergyCamera)
        this.nowselectedListtwo = nowselectedList;
        if (nowselectedList && nowselectedList.length > 0) {
          this.addActive = true;
        } else this.addActive = false;
      } else {
        this.addActive = false;
      }
    },
    del() {
      this.$confirm(`确认删除摄像头？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'myClass'
      })
        .then(() => {
          this.delmessage();
        })
        .catch(() => {});
    },
    delmessage() {
      nowpagereq.delListFarmingTypelist({ noList: this.nowselectedList }).then(res => {
        if (res.code === 1) {
          this.getTableDataListone();
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      });
    },

    // 添加
    add() {
      this.canInput = true;
      if (this.nowselectedListtwo.length === 0) {
        return this.$message.warning('请先选择数据');
      }
      nowpagereq
        .addFarmingTypelist({
          cameraList: this.nowselectedListtwo,
          organizationNo: sessionStorage.organizationNo
        })
        .then(res => {
          if (res.code === 1) {
            this.getTableDataListone();
            this.$refs.tableDatatwo.clearSelection();
            this.$message.success('添加成功');
          } else {
            this.$message.error('添加失败');
          }
        });
      //   } else {
      //   // console.log('error submit!!');
      //     return false;
      //   }
      // })
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    // 添加
    edit(row) {
      this.canInput = true;
      this.formData = JSON.parse(JSON.stringify(row));
      this.nowChanceStau = 'edit';
      this.titleText = '修改';
      this.dialogFormVisible = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    editmet() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          nowpagereq.editFarmingTypelist(this.formData).then(res => {
            if (res.code === 1) {
              this.getTableDataListone();
              this.$refs.tableDatatwo.clearSelection();
              this.$message.success('修改成功');
            } else {
              this.$message.error('修改失败');
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
</style>
